<?php
class ServerBenchmark{

	protected $loops	= 1;
	protected $uris		= array();

	public function __construct( $fileName = "servers.list", $loops = 1 ){
		$this->loops	= abs( $loops );
		if( !file_exists( $fileName ) )
			die( 'File "'.$fileName.'" is not readable' );
		$this->uris	= parse_ini_file( $fileName, TRUE );
		$this->runTests();
		$table	= $this->buildTable();
		$script	= '<script>$(document).ready(function(){$(".tablesorter").tablesorter();});</script>';

		$page	= new UI_HTML_PageFrame();
		$page->addJavaScript( 'http://js.ceusmedia.com/jquery/1.2.3.pack.js' );
		$page->addJavaScript( 'http://js.ceusmedia.com/jquery/tablesorter/2.0.3.min.js' );
		//$page->addStyleSheet( 'http://css.ceusmedia.com/blueprint/reset.css' );
		$page->addStyleSheet( 'http://css.ceusmedia.com/blueprint/typography.css' );
		$page->addStyleSheet( 'http://js.ceusmedia.com/jquery/tablesorter/2.0.3/themes/blue/style.css' );
		$page->addStyleSheet( 'style.css' );
		$page->addHead( $script );
		$page->addBody( '<h2>Server Benchmark</h2>' );
		$page->addBody( $table );
		echo $page->build();
		exit;
	}

	protected function buildTable(){
		$max	= 0;
		foreach( $this->uris as $domain => $data ){
			if( !empty( $data['default'] ) ){
				$max	= $data['time'];
				break;
			}
			if( $data['time'] > $max )
				$max	= $data['time'];	
		}

		$list	= array();
		foreach( $this->uris as $domain => $data )
		{
			$rel	= $data['time'] ? round( $data['time'] / $max * 100 ) : 0;
			$boost	= $data['time'] ? round( $max / $data['time'] * 100 ) - 100 : 0;
			$time	= round( $data['time'] / 1000 / $this->loops );
			$list[]	= require 'table.row.tmpl';
		}
		return require_once 'table.tmpl';
	}

	protected function getRequestTime( $domain, $data ){
		$prot	= !empty( $data['protocol'] ) ? $data['protocol'] : "http";
		$url	= $prot.'://'.$domain.'/'.$data['path'];
		$reader	= new Net_HTTP_Reader();
		if( !empty( $data['username'] ) && !empty( $data['username'] ) )
			$reader->setBasicAuth( $data['username'], $data['password'] );
		$reader->get( $url );
		return $reader->getCurlInfo( 'total_time' ) * 1000 * 1000;
	}

	protected function runTests(){
		for( $i=0; $i<$this->loops; $i++ ){
			foreach( $this->uris as $domain => $data ){
				if( !empty( $data['disabled'] ) ){
					unset( $this->uris[$domain] );
					continue;
				}
				if( !isset( $this->uris[$domain]['time'] ) )
					$this->uris[$domain]['time']	= 0;
				$time	= $this->getRequestTime( $domain, $data );
				if( $time < 1 )
					continue;
				$this->uris[$domain]['time']	+= $time;
			}
		}
	}
}
?>
